package com.test.tinyurl.domain.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;

@RestController
public class UrlController {

    /**
     * 注入redisTemplate
     */
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 根据传入的hashCode找到对应的URL并重定向
     * 1.通过hashCode从redis中获取对应URL
     * 2.对URL进行重定向跳转
     *
     * @param shortLink
     */
    @GetMapping(value = "/{shortLink}")
    public void redirectFullUrl(@NotBlank @PathVariable(value = "shortLink") String shortLink, HttpServletResponse response) throws Exception {

        //通过hashCode从redis中获取对应url
        String fullLink = redisTemplate.opsForValue().get(shortLink);
        if (StringUtils.isBlank(fullLink)) {
            throw new HttpServerErrorException(HttpStatus.NOT_FOUND);
        }

        //对URL进行重定向跳转
        response.sendRedirect(fullLink);
    }
}
